package com.tj.collection.controller.lending;

import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.EntityUtils;
import com.fqgj.common.utils.TimeUtils;
import com.fqgj.exception.common.ApiErrorException;
import com.google.common.collect.Lists;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.bean.ModuleResponse;
import com.tj.collection.controller.lending.request.ClThirdContactsRequest;
import com.tj.collection.controller.lending.response.ClAddressBookSwitchResponse;
import com.tj.collection.controller.lending.response.ClDeviceContactDataResponse;
import com.tj.collection.controller.lending.response.ClEmergencyContactResponse;
import com.tj.collection.controller.lending.response.ClUserHighmarkContactsResponse;
import com.tj.collection.db.dao.ClCommentDao;
import com.tj.collection.db.dao.ClPhoneRecordDao;
import com.tj.collection.db.dao.ClReceiverDao;
import com.tj.collection.db.dao.ClReceiverDetailDao;
import com.tj.collection.db.entity.ClCommentEntity;
import com.tj.collection.db.entity.ClPhoneRecordEntity;
import com.tj.collection.db.entity.ClReceiverDetailEntity;
import com.tj.collection.db.entity.ClReceiverEntity;
import com.tj.collection.service.ContactApplication;
import com.tj.collection.service.dto.DeviceContactDataVO;
import com.tj.collection.utils.ConfigUtil;
import com.tj.collection.utils.IndiaMobileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/12/24
 * Time: 下午5:11
 */
@RestController
@RequestMapping("/collection/v2")
public class ClContactsController {

    @Autowired
    private ClReceiverDao receiverDao;

    @Autowired
    private ClReceiverDetailDao clReceiverDetailDao;

    @Autowired
    private ClCommentDao clCommentDao;

    @Autowired
    private ClPhoneRecordDao clPhoneRecordDao;

    @Autowired
    private ContactApplication contactApplication;

    @Autowired
    private ConfigUtil configUtil;

    /**
     * 查询通讯录状态
     *
     * @return
     */
    @RequestMapping(value = "/addressBook/status/get")
    public ApiResponse<ClAddressBookSwitchResponse> addressBookStatusGet() {
//        return new ApiResponse<>(new ClAddressBookSwitchResponse(configUtil.getAddressBookSwitch() ? 1 : 0));
        return new ApiResponse<>(new ClAddressBookSwitchResponse(1));
    }

    /**
     * 查询highmark通讯录
     *
     * @param clThirdContactsRequest
     * @return
     */
    @RequestMapping("/third/contacts/list")
    public ModuleResponse<ClUserHighmarkContactsResponse> collectionDistributeGet(@RequestBody @Valid ClThirdContactsRequest clThirdContactsRequest) {
        if (!configUtil.getAddressBookShowType().contains("third")) {
            return new ModuleResponse<>(new ClUserHighmarkContactsResponse());
        }
        return new ModuleResponse<>(new ClUserHighmarkContactsResponse());
    }

    /**
     * 催收紧急联系人
     *
     * @return
     */
    @RequestMapping(value = "/emergency/contacts/list")
    public ApiResponse<ClEmergencyContactResponse> profileContactsGet(@RequestBody @Valid ClThirdContactsRequest clThirdContactsRequest) {
        if (!configUtil.getAddressBookShowType().contains("emergency")) {
            return new ApiResponse<>(new ClEmergencyContactResponse());
        }

        ClReceiverEntity clReceiverEntity = receiverDao.selectLastByOrderNo(clThirdContactsRequest.getTradeNo());
        ClReceiverDetailEntity clReceiverDetailEntity = clReceiverDetailDao.selectOneByCollectionNo(clReceiverEntity.getCollectionNo());

        List<ClCommentEntity> clCommentEntityList = clCommentDao.selectLatestCommonByCollectionNo(clReceiverEntity.getCollectionNo());
        List<ClPhoneRecordEntity> clPhoneRecordEntityList = clPhoneRecordDao.selectLatestPhoneRecordByCollectionNo(clReceiverEntity.getCollectionNo());
        ClEmergencyContactResponse contactsInfoVO = new ClEmergencyContactResponse(clReceiverDetailEntity, clCommentEntityList, clPhoneRecordEntityList);
        return new ApiResponse<>(contactsInfoVO);
    }

    /**
     * 获取通讯录
     *
     * @return
     */
    @RequestMapping(value = "/addressbook/contacts/list")
    public ApiResponse<ClDeviceContactDataResponse> addressBookGet(@RequestBody @Valid ClThirdContactsRequest clThirdContactsRequest) {
        if (!configUtil.getAddressBookShowType().contains("addressbook")) {
            return new ApiResponse<>(new ClDeviceContactDataResponse());
        }

        ClReceiverEntity clReceiverEntity = receiverDao.selectLastByOrderNo(clThirdContactsRequest.getTradeNo());
        ClReceiverDetailEntity clReceiverDetailEntity = clReceiverDetailDao.selectOneByCollectionNo(clReceiverEntity.getCollectionNo());

        List<String> contactList = Lists.newArrayList(clReceiverDetailEntity.getContactUrl());

        DeviceContactDataVO deviceContactDataVO = Optional.ofNullable(contactApplication.loadDeviceContactDataV2(contactList, clReceiverDetailEntity.getName(), clReceiverDetailEntity.getMobile()))
                .orElseThrow(() -> new ApiErrorException("get contact address failed"));
        List<ClPhoneRecordEntity> clPhoneRecordEntityList = clPhoneRecordDao.selectLatestPhoneRecordByCollectionNo(clReceiverEntity.getCollectionNo());
        if (CollectionUtils.isNotEmpty(clPhoneRecordEntityList)) {
            Map<String, ClPhoneRecordEntity> clPhoneRecordEntityMap = EntityUtils.makeEntityMap(clPhoneRecordEntityList, "mobile");
            //添加催收备注信息
            deviceContactDataVO.getContacts().forEach(
                    contact -> {
                        ClPhoneRecordEntity clPhoneRecordEntity = clPhoneRecordEntityMap.get(contact.getPhone());
                        if (clPhoneRecordEntity == null) {
                            clPhoneRecordEntity = clPhoneRecordEntityMap.get(IndiaMobileUtil.countryCodeFilter(contact.getPhone()));
                        }
                        if (clPhoneRecordEntity != null) {
                            contact.setCollectionContactRecord(clPhoneRecordEntity.getContent());
                            contact.setCollectionLastContactTime(DateUtil.getDate(clPhoneRecordEntity.getGmtCreate(), "yyyy-MM-dd HH:mm:ss"));
                            contact.setCollectionLastContactTimeIntervalDays(TimeUtils.diffDays(clPhoneRecordEntity.getGmtCreate(), new Date()));
                            contact.setState(clPhoneRecordEntity.getCallingResult());
                        }
                    }
            );
        }
        return new ApiResponse<>(new ClDeviceContactDataResponse(deviceContactDataVO));
    }

}
